using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.InputSystem.Interactions;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
using UnityEngine.UIElements;

public class GameManager : MonoBehaviour
{
    public GameObject PlayerScoreLable;
    public GameObject MultiPlayer;

    private AudioSource audioSource;
    
    public GameObject player;
    public GameObject Basket;

    public GameObject StartCanvas;
    public GameObject GameOverCanvas;
    public Text curScore;
    public Text bestScore;
    
    public ScoreManager scoreManager;

    public GameObject MultiPlayerGameOverCanvas;

    public void Start()
    {
        SwitchGameMode(GameMod.GameMode);
        audioSource = GetComponent<AudioSource>();

        Time.timeScale = 0;
        StartCanvas.SetActive(true);

        TimeManager.isGameOver = false;
        TimeManager.curTime = 0;

    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Time.timeScale = 1;
            StartCanvas.SetActive(false);
        }

    }

    void OnTriggerStay2D(Collider2D other)
    {
         if (other.gameObject.tag == "Player")
        {
            if (TimeManager.isGameOver)
            {
                GameOver();
            }
        }
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Player")
        {
            if (TimeManager.isGameOver)
            {
                GameOver();
            }
        }
    }

    private void GameOver() 
    {
        if (GameMod.GameMode == 0)
        {
            GameOverCanvas.SetActive(true);
            curScore.text = scoreManager.GetScore().ToString();
            if (Load() == -1) Save();
            if (scoreManager.GetScore() > Load()) Save();
            bestScore.text = Load().ToString();
        }
        if (GameMod.GameMode == 1)
        {
            MultiPlayerGameOverCanvas.SetActive(true);
        }
    }

    public void SwitchGameMode(int GameMode)
    {
        if (GameMode == 0)
        {
            MultiPlayer.SetActive(false);
            PlayerScoreLable.SetActive(false);
            TimeManager.curMaxTime = 3;
        } 
        if (GameMode == 1)
        {
            MultiPlayer.SetActive(true);
            PlayerScoreLable.SetActive(true);
            TimeManager.curMaxTime = 90;
        }
    }

    public void Save()
    {
        PlayerPrefs.SetInt("best_score", scoreManager.GetScore());
        PlayerPrefs.Save();
    }

    public int Load()
    {
        int save = -1;
        save = PlayerPrefs.GetInt("best_score");
        //print(save);
        return save;
    }
}
